{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Protein-ligand Docking tutorial using BioExcel Building Blocks (biobb)\n",
    "### -- *PDBe REST-API Version* --\n",
    "\n",
    "***\n",
    "This tutorial aims to illustrate the process of **protein-ligand docking**, step by step, using the **BioExcel Building Blocks library (biobb)**. The particular example used is the **Mitogen-activated protein kinase 14** (p38-α) protein (PDB code [3LFA](https://www.rcsb.org/structure/3LFA)), a well-known **Protein Kinase enzyme**, \n",
    " in complex with the FDA-approved **Dasatinib**, (PDB Ligand code [1N1](https://www.rcsb.org/ligand/1N1), DrugBank Ligand Code [DB01254](https://go.drugbank.com/drugs/DB01254)), a small molecule **kinase inhibitor** used for the treatment of **lymphoblastic** or **chronic myeloid leukemia** with resistance or intolerance to prior therapy.\n",
    " \n",
    "The tutorial will guide you through the process of identifying the **active site cavity** (pocket) and the final prediction of the **protein-ligand complex**. \n",
    "\n",
    "Please note that **docking algorithms**, and in particular, **AutoDock Vina** program used in this tutorial, are **non-deterministic**. That means that results obtained when running the workflow **could be diferent** from the ones we obtained during the writing of this tutorial (see [AutoDock Vina manual](http://vina.scripps.edu/manual.html)). We invite you to try the docking process several times to verify this behaviour. \n",
    "***\n",
    "\n",
    "<div style=\"background:#b5e0dd; padding: 15px;\"><strong>Important:</strong> it is recommended to execute this tutorial step by step (not as a single workflow execution, <strong><em>Run All</em></strong> mode), as it has interactive selections.</div>\n",
    "\n",
    "## Settings\n",
    "\n",
    "### Biobb modules used\n",
    "\n",
    " - [biobb_io](https://github.com/bioexcel/biobb_io): Tools to fetch biomolecular data from public databases.\n",
    " - [biobb_structure_utils](https://github.com/bioexcel/biobb_structure_utils): Tools to modify or extract information from a PDB structure file.\n",
    " - [biobb_chemistry](https://github.com/bioexcel/biobb_chemistry): Tools to perform chemoinformatics processes.\n",
    " - [biobb_vs](https://github.com/bioexcel/biobb_vs): Tools to perform virtual screening studies.\n",
    " \n",
    "### Auxiliar libraries used\n",
    "\n",
    " - [nb_conda_kernels](https://github.com/Anaconda-Platform/nb_conda_kernels): Enables a Jupyter Notebook or JupyterLab application in one conda environment to access kernels for Python, R, and other languages found in other environments.\n",
    " - [nglview](http://nglviewer.org/#nglview): Jupyter/IPython widget to interactively view molecular structures and trajectories in notebooks.\n",
    " - [ipywidgets](https://github.com/jupyter-widgets/ipywidgets): Interactive HTML widgets for Jupyter notebooks and the IPython kernel.\n",
    "\n",
    "### Conda Installation and Launch\n",
    "\n",
    "```console\n",
    "git clone https://github.com/bioexcel/biobb_wf_virtual-screening.git\n",
    "cd biobb_wf_virtual-screening\n",
    "conda env create -f conda_env/environment.yml\n",
    "conda activate biobb_VS_tutorial\n",
    "jupyter-nbextension enable --py --user widgetsnbextension\n",
    "jupyter-nbextension enable --py --user nglview\n",
    "jupyter-notebook biobb_wf_virtual-screening/notebooks/ebi_api/wf_vs_ebi_api.ipynb\n",
    "  ``` \n",
    "\n",
    "***\n",
    "## Pipeline steps\n",
    " 1. [Input Parameters](#input)\n",
    " 2. [Fetching PDB Structure](#fetch)\n",
    " 3. [Extract Protein Structure](#extractProtein)\n",
    " 4. [Computing Protein Cavities (PDBe REST-API)](#pdbe)\n",
    " 5. [Select Binding Site](#pdbeSelect)\n",
    " 6. [Generating Cavity Box ](#cavityBox)\n",
    " 7. [Downloading Small Molecule](#downloadSmallMolecule)\n",
    " 8. [Converting Small Molecule](#sdf2pdb)\n",
    " 9. [Preparing Small Molecule (ligand) for Docking](#ligand_pdb2pdbqt)\n",
    " 10. [Preparing Target Protein for Docking](#protein_pdb2pdbqt)\n",
    " 11. [Running the Docking](#docking)\n",
    " 12. [Extract a Docking Pose](#extractPose)\n",
    " 13. [Converting Ligand Pose to PDB format](#pdbqt2pdb)\n",
    " 14. [Superposing Ligand Pose to the Target Protein Structure](#catPdb)\n",
    " 15. [Comparing final result with experimental structure](#viewFinal)\n",
    " 16. [Questions & Comments](#questions)\n",
    " \n",
    "***\n",
    "<img src=\"https://bioexcel.eu/wp-content/uploads/2019/04/Bioexcell_logo_1080px_transp.png\" alt=\"Bioexcel2 logo\"\n",
    "\ttitle=\"Bioexcel2 logo\" width=\"400\" />\n",
    "***\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id=\"input\"></a>\n",
    "## Input parameters\n",
    "**Input parameters** needed:\n",
    "\n",
    " - **pdb_code**: PDB code of the experimental complex structure (if exists).<br>\n",
    "In this particular example, the **p38α** structure in complex with the **Dasatinib drug** was experimentally solved and deposited in the **PDB database** under the **3LFA** PDB code. The protein structure from this PDB file will be used as a **target protein** for the **docking process**, after stripping the **small molecule**. An **APO structure**, or any other structure from the **p38α** [cluster 100](https://www.rcsb.org/search?request=%7B%22query%22%3A%7B%22type%22%3A%22terminal%22%2C%22service%22%3A%22sequence%22%2C%22parameters%22%3A%7B%22target%22%3A%22pdb_protein_sequence%22%2C%22value%22%3A%22RPTFYRQELNKTIWEVPERYQNLSPVGSGAYGSVCAAFDTKTGLRVAVKKLSRPFQSIIHAKRTYRELRLLKHMKHENVIGLLDVFTPARSLEEFNDVYLVTHLMGADLNNIVKCQKLTDDHVQFLIYQILRGLKYIHSADIIHRDLKPSNLAVNEDCELKILDFGLARHTDDEMTGYVATRWYRAPEIMLNWMHYNQTVDIWSVGCIMAELLTGRTLFPGTDHIDQLKLILRLVGTPGAELLKKISSESARNYIQSLTQMPKMNFANVFIGANPLAVDLLEKMLVLDSDKRITAAQALAHAYFAQYHDPDDEPVADPYDQSFESRDLLIDEWKSLTYDEVISFVPPP%22%2C%22identity_cutoff%22%3A1%2C%22evalue_cutoff%22%3A0.1%7D%2C%22node_id%22%3A0%7D%2C%22return_type%22%3A%22polymer_entity%22%2C%22request_options%22%3A%7B%22pager%22%3A%7B%22start%22%3A0%2C%22rows%22%3A25%7D%2C%22scoring_strategy%22%3A%22combined%22%2C%22sort%22%3A%5B%7B%22sort_by%22%3A%22score%22%2C%22direction%22%3A%22desc%22%7D%5D%7D%2C%22request_info%22%3A%7B%22src%22%3A%22ui%22%2C%22query_id%22%3A%22bea5861f8b38a9e25a3e626b39d6bcbf%22%7D%7D) (sharing a 100% of sequence similarity with the **p38α** structure) could also be used as a **target protein**. This structure of the **protein-ligand complex** will be also used in the last step of the tutorial to check **how close** the resulting **docking pose** is from the known **experimental structure**. \n",
    " -----\n",
    " - **ligandCode**: Ligand PDB code (3-letter code) for the small molecule (e.g. 1N1).<br>\n",
    "In this particular example, the small molecule chosen for the tutorial is the FDA-approved drug **Dasatinib** (PDB Code 1N1), a **tyrosine kinase inhibitor**, used in [lymphoblastic or chronic myeloid leukemia](https://go.drugbank.com/drugs/DB01254).\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [],
   "source": [
    "import nglview\n",
    "import ipywidgets\n",
    "\n",
    "pdb_code = \"3LFA\"         # P38 + Dasatinib\n",
    "\n",
    "ligand_code = \"1N1\"       # Dasatinib"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id=\"fetch\"></a>\n",
    "***\n",
    "## Fetching PDB structure\n",
    "Downloading **PDB structure** with the **protein molecule** from the PDBe database.<br>\n",
    "Alternatively, a **PDB file** can be used as starting structure. <br>\n",
    "***\n",
    "**Building Blocks** used:\n",
    " - [Pdb](https://biobb-io.readthedocs.io/en/latest/api.html#module-api.pdb) from **biobb_io.api.pdb**\n",
    "***"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2021-05-17 12:45:06,136 [MainThread  ] [INFO ]  Downloading: 3lfa from: https://www.ebi.ac.uk/pdbe/entry-files/download/pdb3lfa.ent\n",
      "/anaconda3/envs/biobb_VS_tutorial/lib/python3.7/site-packages/urllib3/connectionpool.py:1020: InsecureRequestWarning: Unverified HTTPS request is being made to host 'www.ebi.ac.uk'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n",
      "  InsecureRequestWarning,\n",
      "2021-05-17 12:45:06,695 [MainThread  ] [INFO ]  Writting pdb to: download.pdb\n",
      "2021-05-17 12:45:06,698 [MainThread  ] [INFO ]  Filtering lines NOT starting with one of these words: ['ATOM', 'HETATM']\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "0"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from biobb_io.api.pdb import pdb\n",
    "\n",
    "download_pdb = \"download.pdb\"\n",
    "prop = {\n",
    "  \"pdb_code\": pdb_code,\n",
    "  \"filter\": [\"ATOM\", \"HETATM\"]\n",
    "}\n",
    "\n",
    "pdb(output_pdb_path=download_pdb,\n",
    "    properties=prop)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id=\"vis3D\"></a>\n",
    "### Visualizing 3D structure\n",
    "Visualizing the downloaded/given **PDB structure** using **NGL**.<br><br>\n",
    "Note (and try to identify) the **Dasatinib small molecule (1N1)** and the **detergent (β-octyl glucoside) (BOG)** used in the experimental reservoir solution to obtain the crystal."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "be1209779e7947f487a7d54f64d5d8e4",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "NGLWidget()"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "view = nglview.show_structure_file(download_pdb, default=True)\n",
    "view.center()\n",
    "view._remote_call('setSize', target='Widget', args=['','600px'])\n",
    "\n",
    "view.render_image()\n",
    "view.download_image(filename='ngl1.png')\n",
    "view"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<img src='ngl1.png'></img>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id=\"extractProtein\"></a>\n",
    "***\n",
    "## Extract Protein Structure\n",
    "Extract **protein structure** from the **downloaded PDB file**. Removing **any extra molecule** (ligands, ions, water molecules). <br><br>\n",
    "The **protein structure** will be used as a **target** in the **protein-ligand docking process**. \n",
    "***\n",
    "**Building Blocks** used:\n",
    " - [extract_molecule](https://biobb-structure-utils.readthedocs.io/en/latest/utils.html#module-utils.extract_molecule) from **biobb_structure_utils.utils.extract_molecule**\n",
    "***"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2021-05-17 12:45:11,208 [MainThread  ] [INFO ]  Creating 95dad78e-6572-4ced-8157-0a3d58965f0f temporary folder\n",
      "2021-05-17 12:45:11,916 [MainThread  ] [INFO ]  check_structure -i /home/gbayarri_local/projects/BioBB/tutorials/biobb_wf_virtual-screening/biobb_wf_virtual-screening/notebooks/ebi_api/download.pdb -o pdb_protein.pdb --force_save --non_interactive command_list --list 95dad78e-6572-4ced-8157-0a3d58965f0f/extract_prot.lst\n",
      "\n",
      "2021-05-17 12:45:11,918 [MainThread  ] [INFO ]  Exit code 0\n",
      "\n",
      "2021-05-17 12:45:11,918 [MainThread  ] [INFO ]  ===============================================================================\n",
      "=                   BioBB structure checking utility v3.7.2                   =\n",
      "=                 A. Hospital, P. Andrio, J.L. Gelpi 2018-20                  =\n",
      "===============================================================================\n",
      "\n",
      "Warning: sequence features only available in mmCIF format or with external fasta input\n",
      "Structure /home/gbayarri_local/projects/BioBB/tutorials/biobb_wf_virtual-screening/biobb_wf_virtual-screening/notebooks/ebi_api/download.pdb loaded\n",
      " Title: \n",
      " Experimental method: unknown\n",
      " Resolution: None A\n",
      "\n",
      " Num. models: 1\n",
      " Num. chains: 1 (A: Protein)\n",
      " Num. residues:  483\n",
      " Num. residues with ins. codes:  0\n",
      " Num. HETATM residues:  150\n",
      " Num. ligands or modified residues:  2\n",
      " Num. water mol.:  148\n",
      " Num. atoms:  2874\n",
      "Modified residues found\n",
      "1N1 A361\n",
      "Small mol ligands found\n",
      "BOG A1000\n",
      "\n",
      "\n",
      "Step 1: ligands --remove All\n",
      "\n",
      "Running ligands. Options: --remove All\n",
      "2 Ligands detected\n",
      " 1N1 A361\n",
      " BOG A1000\n",
      "Ligands removed All (2)\n",
      "\n",
      "Step 2: water --remove Yes\n",
      "\n",
      "Running water. Options: --remove Yes\n",
      "148 Water molecules detected\n",
      "148 Water molecules removed\n",
      "Command list completed\n",
      "Final Num. models: 1\n",
      "Final Num. chains: 1 (A: Protein)\n",
      "Final Num. residues:  333\n",
      "Final Num. residues with ins. codes:  0\n",
      "Final Num. HETATM residues:  0\n",
      "Final Num. ligands or modified residues:  0\n",
      "Final Num. water mol.:  0\n",
      "Final Num. atoms:  2673\n",
      "Structure saved on pdb_protein.pdb\n",
      "\n",
      "2021-05-17 12:45:11,920 [MainThread  ] [INFO ]  Removing 95dad78e-6572-4ced-8157-0a3d58965f0f temporary folder\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "0"
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from biobb_structure_utils.utils.extract_molecule import extract_molecule\n",
    "\n",
    "pdb_protein = \"pdb_protein.pdb\"\n",
    "\n",
    "extract_molecule(input_structure_path=download_pdb,\n",
    "             output_molecule_path = pdb_protein)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id=\"vis3D\"></a>\n",
    "### Visualizing 3D structure\n",
    "Visualizing the downloaded/given **PDB structure** using **NGL**.<br><br>\n",
    "Note that the **small molecules** included in the original structure are now gone. The new structure only contains the **protein molecule**, which will be used as a **target** for the **protein-ligand docking**. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "0dab937069db42d39ff9cd4ee36b1df2",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "NGLWidget()"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "view = nglview.show_structure_file(pdb_protein, default=False)\n",
    "view.add_representation(repr_type='cartoon', \n",
    "                        selection='not het',\n",
    "                       colorScheme = 'atomindex')\n",
    "view.center()\n",
    "view._remote_call('setSize', target='Widget', args=['','600px'])\n",
    "\n",
    "\n",
    "\n",
    "view.render_image()\n",
    "view.download_image(filename='ngl2.png')\n",
    "view"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<img src='ngl2.png'></img>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id=\"pdbe\"></a>\n",
    "***\n",
    "## Computing Protein Cavities (PDBe REST-API)\n",
    "Identifying the **protein cavities** (pockets) using the [**PDBe REST-API**](https://www.ebi.ac.uk/pdbe/api/doc/).<br>\n",
    "\n",
    "These **cavities** will be then used in the **docking procedure** to try to find the **best region of the protein surface** where the small molecule can **bind**. <br><br>\n",
    "Although in this particular example we already know the **binding site** region, as we started from a **protein-ligand complex** structure where the ligand was located in the same **binding site** as **Dasatinib** is binding, the **PDBe REST-API** can be used to automatically identify and extract the possible **binding sites** of our **target protein** from the PDB file annotations. This **REST-API endpoint** provides details on **binding sites** from the PDB files (or mmcif) information, such as **ligands**, **residues in the site** or **description of the site**. <br>\n",
    "\n",
    "\n",
    "***\n",
    "**Building Blocks** used:\n",
    " - [api_binding_site](https://biobb-io.readthedocs.io/en/latest/api.html#module-api.api_binding_site) from **biobb_io.api.api_binding_site**\n",
    "***"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2021-05-17 12:45:16,458 [MainThread  ] [INFO ]  Getting binding sites from: https://www.ebi.ac.uk/pdbe/api/pdb/entry/binding_sites/3lfa\n",
      "2021-05-17 12:45:16,711 [MainThread  ] [INFO ]  2 binding sites found\n",
      "2021-05-17 12:45:16,713 [MainThread  ] [INFO ]  Writting json to: residues.json\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "0"
      ]
     },
     "execution_count": 29,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from biobb_io.api.api_binding_site import api_binding_site\n",
    "\n",
    "residues_json = \"residues.json\"\n",
    "prop = {\n",
    "  \"pdb_code\": pdb_code\n",
    "}\n",
    "\n",
    "api_binding_site(output_json_path=residues_json,\n",
    "    properties=prop)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id=\"checkJson\"></a>\n",
    "### Checking binding site output (json)\n",
    "Checking the **PDBe REST-API** output from the **json file**. Every **pocket** has a separated entry in the json output, with information such as: **residues forming the cavity, details of the cavity**, and **evidence used to detect the cavity**. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\n",
      "    \"3lfa\": [\n",
      "        {\n",
      "            \"details\": \"BINDING SITE FOR RESIDUE BOG\",\n",
      "            \"evidence_code\": \"Software\",\n",
      "            \"ligand_residues\": [\n",
      "                {\n",
      "                    \"author_insertion_code\": null,\n",
      "                    \"author_residue_number\": 1000,\n",
      "                    \"chain_id\": \"A\",\n",
      "                    \"chem_comp_id\": \"BOG\",\n",
      "                    \"entity_id\": 3,\n",
      "                    \"residue_number\": 1,\n",
      "                    \"struct_asym_id\": \"C\"\n",
      "                }\n",
      "            ],\n",
      "            \"site_id\": \"AC2\",\n",
      "            \"site_residues\": [\n",
      "                {\n",
      "                    \"author_insertion_code\": null,\n",
      "                    \"author_residue_number\": 294,\n",
      "                    \"chain_id\": \"A\",\n",
      "                    \"chem_comp_id\": \"ASP\",\n",
      "                    \"entity_id\": 1,\n",
      "                    \"residue_number\": 294,\n",
      "                    \"struct_asym_id\": \"A\",\n",
      "                    \"symmetry_symbol\": \"1_555\"\n",
      "                },\n",
      "                {\n",
      "                    \"author_insertion_code\": null,\n",
      "                    \"author_residue_number\": 293,\n",
      "                    \"chain_id\": \"A\",\n",
      "                    \"chem_comp_id\": \"SER\",\n",
      "                    \"entity_id\": 1,\n",
      "                    \"residue_number\": 293,\n",
      "                    \"struct_asym_id\": \"A\",\n",
      "                    \"symmetry_symbol\": \"1_555\"\n",
      "                },\n",
      "                {\n",
      "                    \"author_insertion_code\": null,\n",
      "                    \"author_residue_number\": 292,\n",
      "                    \"chain_id\": \"A\",\n",
      "                    \"chem_comp_id\": \"ASP\",\n",
      "                    \"entity_id\": 1,\n",
      "                    \"residue_number\": 292,\n",
      "                    \"struct_asym_id\": \"A\",\n",
      "                    \"symmetry_symbol\": \"1_555\"\n",
      "                },\n",
      "                {\n",
      "                    \"author_insertion_code\": null,\n",
      "                    \"author_residue_number\": 192,\n",
      "                    \"chain_id\": \"A\",\n",
      "                    \"chem_comp_id\": \"GLU\",\n",
      "                    \"entity_id\": 1,\n",
      "                    \"residue_number\": 192,\n",
      "                    \"struct_asym_id\": \"A\",\n",
      "                    \"symmetry_symbol\": \"1_555\"\n",
      "                },\n",
      "                {\n",
      "                    \"author_insertion_code\": null,\n",
      "                    \"author_residue_number\": 197,\n",
      "                    \"chain_id\": \"A\",\n",
      "                    \"chem_comp_id\": \"TRP\",\n",
      "                    \"entity_id\": 1,\n",
      "                    \"residue_number\": 197,\n",
      "                    \"struct_asym_id\": \"A\",\n",
      "                    \"symmetry_symbol\": \"1_555\"\n",
      "                },\n",
      "                {\n",
      "                    \"author_insertion_code\": null,\n",
      "                    \"author_residue_number\": 199,\n",
      "                    \"chain_id\": \"A\",\n",
      "                    \"chem_comp_id\": \"HIS\",\n",
      "                    \"entity_id\": 1,\n",
      "                    \"residue_number\": 199,\n",
      "                    \"struct_asym_id\": \"A\",\n",
      "                    \"symmetry_symbol\": \"1_555\"\n",
      "                },\n",
      "                {\n",
      "                    \"author_insertion_code\": null,\n",
      "                    \"author_residue_number\": 200,\n",
      "                    \"chain_id\": \"A\",\n",
      "                    \"chem_comp_id\": \"TYR\",\n",
      "                    \"entity_id\": 1,\n",
      "                    \"residue_number\": 200,\n",
      "                    \"struct_asym_id\": \"A\",\n",
      "                    \"symmetry_symbol\": \"1_555\"\n",
      "                },\n",
      "                {\n",
      "                    \"author_insertion_code\": null,\n",
      "                    \"author_residue_number\": 246,\n",
      "                    \"chain_id\": \"A\",\n",
      "                    \"chem_comp_id\": \"LEU\",\n",
      "                    \"entity_id\": 1,\n",
      "                    \"residue_number\": 246,\n",
      "                    \"struct_asym_id\": \"A\",\n",
      "                    \"symmetry_symbol\": \"1_555\"\n",
      "                },\n",
      "                {\n",
      "                    \"author_insertion_code\": null,\n",
      "                    \"author_residue_number\": 249,\n",
      "                    \"chain_id\": \"A\",\n",
      "                    \"chem_comp_id\": \"LYS\",\n",
      "                    \"entity_id\": 1,\n",
      "                    \"residue_number\": 249,\n",
      "                    \"struct_asym_id\": \"A\",\n",
      "                    \"symmetry_symbol\": \"1_555\"\n",
      "                },\n",
      "                {\n",
      "                    \"author_insertion_code\": null,\n",
      "                    \"author_residue_number\": 291,\n",
      "                    \"chain_id\": \"A\",\n",
      "                    \"chem_comp_id\": \"LEU\",\n",
      "                    \"entity_id\": 1,\n",
      "                    \"residue_number\": 291,\n",
      "                    \"struct_asym_id\": \"A\",\n",
      "                    \"symmetry_symbol\": \"1_555\"\n",
      "                },\n",
      "                {\n",
      "                    \"author_insertion_code\": null,\n",
      "                    \"author_residue_number\": 418,\n",
      "                    \"chain_id\": \"A\",\n",
      "                    \"chem_comp_id\": \"HOH\",\n",
      "                    \"entity_id\": 4,\n",
      "                    \"residue_number\": 57,\n",
      "                    \"struct_asym_id\": \"D\",\n",
      "                    \"symmetry_symbol\": \"1_555\"\n",
      "                },\n",
      "                {\n",
      "                    \"author_insertion_code\": null,\n",
      "                    \"author_residue_number\": 388,\n",
      "                    \"chain_id\": \"A\",\n",
      "                    \"chem_comp_id\": \"HOH\",\n",
      "                    \"entity_id\": 4,\n",
      "                    \"residue_number\": 27,\n",
      "                    \"struct_asym_id\": \"D\",\n",
      "                    \"symmetry_symbol\": \"1_555\"\n",
      "                },\n",
      "                {\n",
      "                    \"author_insertion_code\": null,\n",
      "                    \"author_residue_number\": 485,\n",
      "                    \"chain_id\": \"A\",\n",
      "                    \"chem_comp_id\": \"HOH\",\n",
      "                    \"entity_id\": 4,\n",
      "                    \"residue_number\": 124,\n",
      "                    \"struct_asym_id\": \"D\",\n",
      "                    \"symmetry_symbol\": \"1_555\"\n",
      "                }\n",
      "            ]\n",
      "        },\n",
      "        {\n",
      "            \"details\": \"BINDING SITE FOR RESIDUE 1N1\",\n",
      "            \"evidence_code\": \"Software\",\n",
      "            \"ligand_residues\": [\n",
      "                {\n",
      "                    \"author_insertion_code\": null,\n",
      "                    \"author_residue_number\": 361,\n",
      "                    \"chain_id\": \"A\",\n",
      "                    \"chem_comp_id\": \"1N1\",\n",
      "                    \"entity_id\": 2,\n",
      "                    \"residue_number\": 1,\n",
      "                    \"struct_asym_id\": \"B\"\n",
      "                }\n",
      "            ],\n",
      "            \"site_id\": \"AC1\",\n",
      "            \"site_residues\": [\n",
      "                {\n",
      "                    \"author_insertion_code\": null,\n",
      "                    \"author_residue_number\": 30,\n",
      "                    \"chain_id\": \"A\",\n",
      "                    \"chem_comp_id\": \"VAL\",\n",
      "                    \"entity_id\": 1,\n",
      "                    \"residue_number\": 30,\n",
      "                    \"struct_asym_id\": \"A\",\n",
      "                    \"symmetry_symbol\": \"1_555\"\n",
      "                },\n",
      "                {\n",
      "                    \"author_insertion_code\": null,\n",
      "                    \"author_residue_number\": 51,\n",
      "                    \"chain_id\": \"A\",\n",
      "                    \"chem_comp_id\": \"ALA\",\n",
      "                    \"entity_id\": 1,\n",
      "                    \"residue_number\": 51,\n",
      "                    \"struct_asym_id\": \"A\",\n",
      "                    \"symmetry_symbol\": \"1_555\"\n",
      "                },\n",
      "                {\n",
      "                    \"author_insertion_code\": null,\n",
      "                    \"author_residue_number\": 71,\n",
      "                    \"chain_id\": \"A\",\n",
      "                    \"chem_comp_id\": \"GLU\",\n",
      "                    \"entity_id\": 1,\n",
      "                    \"residue_number\": 71,\n",
      "                    \"struct_asym_id\": \"A\",\n",
      "                    \"symmetry_symbol\": \"1_555\"\n",
      "                },\n",
      "                {\n",
      "                    \"author_insertion_code\": null,\n",
      "                    \"author_residue_number\": 104,\n",
      "                    \"chain_id\": \"A\",\n",
      "                    \"chem_comp_id\": \"LEU\",\n",
      "                    \"entity_id\": 1,\n",
      "                    \"residue_number\": 104,\n",
      "                    \"struct_asym_id\": \"A\",\n",
      "                    \"symmetry_symbol\": \"1_555\"\n",
      "                },\n",
      "                {\n",
      "                    \"author_insertion_code\": null,\n",
      "                    \"author_residue_number\": 106,\n",
      "                    \"chain_id\": \"A\",\n",
      "                    \"chem_comp_id\": \"THR\",\n",
      "                    \"entity_id\": 1,\n",
      "                    \"residue_number\": 106,\n",
      "                    \"struct_asym_id\": \"A\",\n",
      "                    \"symmetry_symbol\": \"1_555\"\n",
      "                },\n",
      "                {\n",
      "                    \"author_insertion_code\": null,\n",
      "                    \"author_residue_number\": 107,\n",
      "                    \"chain_id\": \"A\",\n",
      "                    \"chem_comp_id\": \"HIS\",\n",
      "                    \"entity_id\": 1,\n",
      "                    \"residue_number\": 107,\n",
      "                    \"struct_asym_id\": \"A\",\n",
      "                    \"symmetry_symbol\": \"1_555\"\n",
      "                },\n",
      "                {\n",
      "                    \"author_insertion_code\": null,\n",
      "                    \"author_residue_number\": 109,\n",
      "                    \"chain_id\": \"A\",\n",
      "                    \"chem_comp_id\": \"MET\",\n",
      "                    \"entity_id\": 1,\n",
      "                    \"residue_number\": 109,\n",
      "                    \"struct_asym_id\": \"A\",\n",
      "                    \"symmetry_symbol\": \"1_555\"\n",
      "                },\n",
      "                {\n",
      "                    \"author_insertion_code\": null,\n",
      "                    \"author_residue_number\": 438,\n",
      "                    \"chain_id\": \"A\",\n",
      "                    \"chem_comp_id\": \"HOH\",\n",
      "                    \"entity_id\": 4,\n",
      "                    \"residue_number\": 77,\n",
      "                    \"struct_asym_id\": \"D\",\n",
      "                    \"symmetry_symbol\": \"1_555\"\n",
      "                }\n",
      "            ]\n",
      "        }\n",
      "    ]\n",
      "}\n"
     ]
    }
   ],
   "source": [
    "import json\n",
    "\n",
    "with open(residues_json) as json_file: \n",
    "    data = json.load(json_file)\n",
    "    print(json.dumps(data, indent=4))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id=\"pdbeSelect\"></a>\n",
    "### Select binding site (cavity)\n",
    "Select a specific **binding site** (cavity) from the obtained list to be used in the **docking procedure**. <br>\n",
    "\n",
    "If the **PDBe REST-API** has successfully identified the correct **binding site**, which we know from the original **protein-ligand structure**, it just needs to be selected. In this particular example, the cavity we are interested in is the **binding site number 1**. <br>\n",
    "\n",
    "Choose a **binding site** from the **DropDown list**:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "9534fd70722a4ce39ca14694c8152add",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Dropdown(description='Binding Site:', options=(('binding_site0', 0), ('binding_site1', 1)), value=0)"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "bindingSites = {}\n",
    "bsites = []\n",
    "for i, item in enumerate(data[pdb_code.lower()]):\n",
    "    bindingSites[i] = []\n",
    "    bsites.append(('binding_site' + str(i), i))\n",
    "    for res in item['site_residues']:\n",
    "        bindingSites[i].append(res['author_residue_number'])\n",
    "#    print('Residue id\\'s for binding site %d: %s' % (i, ', '.join(str(v) for v in bindingSites[i])))\n",
    "        \n",
    "mdsel = ipywidgets.Dropdown(\n",
    "    options=bsites,\n",
    "    description='Binding Site:',\n",
    "    disabled=False,\n",
    ")\n",
    "display(mdsel)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id=\"viewPockets\"></a>\n",
    "### Visualizing selected binding site (cavity)\n",
    "Visualizing the selected **binding site** (cavity) using **NGL viewer**.<br>\n",
    "\n",
    "**Protein residues** forming the **cavity** are represented in **pink-colored surface**. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "7962a180ad5f49ceb60df5999f01b0df",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "NGLWidget()"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "view = nglview.show_structure_file(download_pdb, default=False)\n",
    "\n",
    "view.add_representation(repr_type='cartoon', \n",
    "                        selection='not het',\n",
    "                        opacity=.2,\n",
    "                        color='#cccccc')\n",
    "\n",
    "view.add_representation(repr_type='surface', \n",
    "                        selection=', '.join(str(v) for v in bindingSites[mdsel.value]), \n",
    "                        color='pink',\n",
    "                        lowResolution= True,\n",
    "                        # 0: low resolution \n",
    "                        smooth=1 )\n",
    "\n",
    "view.center()\n",
    "view._remote_call('setSize', target='Widget', args=['','600px'])\n",
    "\n",
    "\n",
    "view.render_image()\n",
    "view.download_image(filename='ngl3.png')\n",
    "view"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<img src='ngl3.png'></img>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id=\"cavityBox\"></a>\n",
    "***\n",
    "## Generating Cavity Box \n",
    "Generating a **box** surrounding the selected **protein cavity** (pocket), to be used in the **docking procedure**. The **box** is defining the region on the **surface** of the **protein target** where the **docking program** should explore a possible **ligand dock**.<br>\n",
    "An offset of **12 Angstroms** is used to generate a **big enough box** to fit the **small molecule** and its possible rotations.<br>\n",
    "\n",
    "***\n",
    "**Building Blocks** used:\n",
    " - [box_residues](https://biobb-vs.readthedocs.io/en/latest/utils.html#module-utils.box_residues) from **biobb_vs.utils.box_residues**\n",
    "***"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2021-05-17 12:45:28,702 [MainThread  ] [INFO ]  Loading input PDB structure download.pdb\n",
      "2021-05-17 12:45:28,768 [MainThread  ] [INFO ]  Mapping residue structure into input structure\n",
      "2021-05-17 12:45:28,770 [MainThread  ] [INFO ]  Cannot match all the residues listed in 30, 51, 71, 104, 106, 107, 109, 438 into download.pdb. Found 7 out of 8\n",
      "2021-05-17 12:45:28,771 [MainThread  ] [INFO ]  Binding site center (Angstroms):     23.913    -2.702   -23.513\n",
      "2021-05-17 12:45:28,774 [MainThread  ] [INFO ]  Binding site size (Angstroms):       17.776    23.257    22.986\n",
      "2021-05-17 12:45:28,776 [MainThread  ] [INFO ]  Volume (cubic Angstroms): 76020\n",
      "2021-05-17 12:45:28,778 [MainThread  ] [INFO ]  Adding box coordinates\n",
      "2021-05-17 12:45:28,782 [MainThread  ] [INFO ]  Saving output PDB file (with box setting annotations): box.pdb\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "0"
      ]
     },
     "execution_count": 33,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from biobb_vs.utils.box_residues import box_residues\n",
    "\n",
    "output_box = \"box.pdb\"\n",
    "prop = {\n",
    "    \"resid_list\": bindingSites[mdsel.value],\n",
    "    \"offset\": 12,\n",
    "    \"box_coordinates\": True\n",
    "}\n",
    "\n",
    "box_residues(#input_pdb_path = pdb_single_chain,\n",
    "            input_pdb_path = download_pdb,\n",
    "            output_pdb_path = output_box,\n",
    "            properties=prop)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id=\"vis3D\"></a>\n",
    "### Visualizing binding site box in 3D structure\n",
    "Visualizing the **protein structure**, the **selected cavity**, and the **generated box**, all together using **NGL** viewer. Using the **original structure** with the **small ligand** inside (Dasatinib, [1N1](https://www.rcsb.org/ligand/1N1)), to check that the **selected cavity** is placed in the **same region** as the **original ligand**. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 60,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "8bd97f32f4ef44b880862f9509b2a7a4",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "NGLWidget()"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "view = nglview.NGLWidget()\n",
    "\n",
    "s = view.add_component(download_pdb)\n",
    "b = view.add_component(output_box)\n",
    "\n",
    "atomPair = [\n",
    "    [ \"9999:Z.ZN1\", \"9999:Z.ZN2\" ],\n",
    "    [ \"9999:Z.ZN2\", \"9999:Z.ZN4\" ],\n",
    "    [ \"9999:Z.ZN4\", \"9999:Z.ZN3\" ],\n",
    "    [ \"9999:Z.ZN3\", \"9999:Z.ZN1\" ],\n",
    "    \n",
    "    [ \"9999:Z.ZN5\", \"9999:Z.ZN6\" ],\n",
    "    [ \"9999:Z.ZN6\", \"9999:Z.ZN8\" ],\n",
    "    [ \"9999:Z.ZN8\", \"9999:Z.ZN7\" ],\n",
    "    [ \"9999:Z.ZN7\", \"9999:Z.ZN5\" ],\n",
    "    \n",
    "    [ \"9999:Z.ZN1\", \"9999:Z.ZN5\" ],\n",
    "    [ \"9999:Z.ZN2\", \"9999:Z.ZN6\" ],\n",
    "    [ \"9999:Z.ZN3\", \"9999:Z.ZN7\" ],\n",
    "    [ \"9999:Z.ZN4\", \"9999:Z.ZN8\" ]\n",
    "]\n",
    "\n",
    "# structure\n",
    "s.add_representation(repr_type='cartoon', \n",
    "                        selection='not het',\n",
    "                        color='#cccccc',\n",
    "                       opacity=.2)\n",
    "# ligands box\n",
    "b.add_representation(repr_type='ball+stick',\n",
    "                     selection='9999',\n",
    "                     color='pink', \n",
    "                     aspectRatio = 8)\n",
    "# lines box\n",
    "b.add_representation(repr_type='distance', \n",
    "                     atomPair= atomPair,\n",
    "                     labelVisible=False,\n",
    "                     color= 'black')\n",
    "\n",
    "# residues\n",
    "s.add_representation(repr_type='surface', \n",
    "                        selection=', '.join(str(v) for v in bindingSites[mdsel.value]), \n",
    "                        color='skyblue',\n",
    "                        lowResolution= True,\n",
    "                        # 0: low resolution \n",
    "                        smooth=1,\n",
    "                        surfaceType= 'av', \n",
    "                        contour=True,\n",
    "                        opacity=0.4,\n",
    "                        useWorker= True,\n",
    "                        wrap= True)\n",
    "\n",
    "\n",
    "view.center()\n",
    "view._remote_call('setSize', target='Widget', args=['','600px'])\n",
    "\n",
    "\n",
    "view.render_image()\n",
    "view.download_image(filename='ngl4.png')\n",
    "view"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<img src='ngl4.png'></img>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id=\"downloadSmallMolecule\"></a>\n",
    "***\n",
    "## Downloading Small Molecule \n",
    "Downloading the desired **small molecule** to be used in the **docking procedure**. <br>\n",
    "In this particular example, the small molecule of interest is the FDA-approved drug **Dasatinib**, with PDB code **1N1**.<br>\n",
    "\n",
    "***\n",
    "**Building Blocks** used:\n",
    " - [ideal_sdf](https://biobb-io.readthedocs.io/en/latest/api.html#module-api.ideal_sdf) from **biobb_io.api.ideal_sdf**\n",
    "***"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2021-05-17 12:45:37,580 [MainThread  ] [INFO ]  Downloading: 1N1 from: ftp://ftp.ebi.ac.uk/pub/databases/msd/pdbechem/files/sdf/1N1.sdf\n",
      "2021-05-17 12:45:37,583 [MainThread  ] [INFO ]  Writting sdf to: ideal.sdf\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "0"
      ]
     },
     "execution_count": 35,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from biobb_io.api.ideal_sdf import ideal_sdf\n",
    "\n",
    "sdf_ideal = \"ideal.sdf\"\n",
    "prop = {\n",
    "  \"ligand_code\": ligand_code\n",
    "}\n",
    "\n",
    "ideal_sdf(output_sdf_path=sdf_ideal,\n",
    "    properties=prop)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id=\"sdf2pdb\"></a>\n",
    "***\n",
    "## Converting Small Molecule \n",
    "Converting the desired **small molecule** to be used in the **docking procedure**, from **SDF** format to **PDB** format using the **OpenBabel chemoinformatics** tool. <br>\n",
    "\n",
    "***\n",
    "**Building Blocks** used:\n",
    " - [babel_convert](https://biobb-chemistry.readthedocs.io/en/latest/babelm.html#module-babelm.babel_convert) from **biobb_chemistry.babelm.babel_convert**\n",
    "***"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2021-05-17 12:45:39,450 [MainThread  ] [INFO ]  Value  is not compatible as a coordinates value\n",
      "2021-05-17 12:45:39,452 [MainThread  ] [INFO ]  Not using any container\n",
      "2021-05-17 12:45:39,499 [MainThread  ] [INFO ]  obabel -isdf ideal.sdf -opdb -Oligand.pdb  \n",
      "\n",
      "2021-05-17 12:45:39,503 [MainThread  ] [INFO ]  Exit code 0\n",
      "\n",
      "2021-05-17 12:45:39,506 [MainThread  ] [INFO ]  1 molecule converted\n",
      "\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "0"
      ]
     },
     "execution_count": 36,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from biobb_chemistry.babelm.babel_convert import babel_convert\n",
    "\n",
    "ligand = \"ligand.pdb\"\n",
    "prop = {\n",
    "    \"input_format\": \"sdf\",\n",
    "    \"output_format\": \"pdb\",\n",
    "    \"obabel_path\": \"obabel\"\n",
    "}\n",
    "\n",
    "babel_convert(input_path = sdf_ideal,\n",
    "            output_path = ligand,\n",
    "            properties=prop)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id=\"ligand_pdb2pdbqt\"></a>\n",
    "***\n",
    "## Preparing Small Molecule (ligand) for Docking\n",
    "Preparing the **small molecule** structure for the **docking procedure**. Converting the **PDB file** to a **PDBQT file** format (AutoDock PDBQT: Protein Data Bank, with Partial Charges (Q), & Atom Types (T)), needed by **AutoDock Vina**. <br><br>\n",
    "The process adds **partial charges** and **atom types** to every atom. Besides, the **ligand flexibility** is also defined in the information contained in the file. The concept of **\"torsion tree\"** is used to represent the **rigid and rotatable** pieces of the **ligand**. A rigid piece (**\"root\"**) is defined, with zero or more rotatable pieces (**\"branches\"**), hanging from the root, and defining the **rotatable bonds**.<br><br>\n",
    "More info about **PDBQT file format** can be found in the [AutoDock FAQ pages](http://autodock.scripps.edu/faqs-help/faq/what-is-the-format-of-a-pdbqt-file).\n",
    "\n",
    "***\n",
    "**Building Blocks** used:\n",
    " - [babel_convert](https://biobb-chemistry.readthedocs.io/en/latest/babelm.html#module-babelm.babel_convert) from **biobb_chemistry.babelm.babel_convert**\n",
    "***"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2021-05-17 12:45:41,635 [MainThread  ] [INFO ]  Value  is not compatible as a coordinates value\n",
      "2021-05-17 12:45:41,637 [MainThread  ] [INFO ]  Not using any container\n",
      "2021-05-17 12:45:41,698 [MainThread  ] [INFO ]  obabel -ipdb ligand.pdb -opdbqt -Oprep_ligand.pdbqt  \n",
      "\n",
      "2021-05-17 12:45:41,699 [MainThread  ] [INFO ]  Exit code 0\n",
      "\n",
      "2021-05-17 12:45:41,700 [MainThread  ] [INFO ]  1 molecule converted\n",
      "\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "0"
      ]
     },
     "execution_count": 37,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from biobb_chemistry.babelm.babel_convert import babel_convert\n",
    "\n",
    "prep_ligand = \"prep_ligand.pdbqt\"\n",
    "prop = {\n",
    "    \"input_format\": \"pdb\",\n",
    "    \"output_format\": \"pdbqt\",\n",
    "    \"obabel_path\": \"obabel\"\n",
    "}\n",
    "\n",
    "babel_convert(input_path = ligand,\n",
    "            output_path = prep_ligand,\n",
    "            properties=prop)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id=\"viewDrug\"></a>\n",
    "### Visualizing small molecule (drug)\n",
    "Visualizing the desired **drug** to be docked to the **target protein**, using **NGL viewer**.<br>\n",
    "- **Left panel**: **PDB-formatted** file, with all hydrogen atoms.\n",
    "- **Right panel**: **PDBqt-formatted** file (AutoDock Vina-compatible), with **united atom model** (only polar hydrogens are placed in the structures to correctly type heavy atoms as hydrogen bond donors).\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 61,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "2b92d64cc7424d69ba31edc2679e270e",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(NGLWidget(), NGLWidget()))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from ipywidgets import HBox\n",
    "\n",
    "v0 = nglview.show_structure_file(ligand)\n",
    "v1 = nglview.show_structure_file(prep_ligand)\n",
    "\n",
    "v0._set_size('500px', '')\n",
    "v1._set_size('500px', '')\n",
    "\n",
    "def on_change(change):\n",
    "    v1._set_camera_orientation(change['new'])\n",
    "    \n",
    "v0.observe(on_change, ['_camera_orientation'])\n",
    "\n",
    "HBox([v0, v1])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<img src='ngl5.png'></img>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id=\"protein_pdb2pdbqt\"></a>\n",
    "***\n",
    "## Preparing Target Protein for Docking\n",
    "Preparing the **target protein** structure for the **docking procedure**. Converting the **PDB file** to a **PDBqt file**, needed by **AutoDock Vina**. Similarly to the previous step, the process adds **partial charges** and **atom types** to every target protein atom. In this case, however, we are not taking into account **receptor flexibility**, although **Autodock Vina** allows some limited flexibility of selected **receptor side chains** [(see the documentation)](https://autodock-vina.readthedocs.io/en/latest/docking_flexible.html).<br>\n",
    "\n",
    "***\n",
    "**Building Blocks** used:\n",
    " - [str_check_add_hydrogens](https://biobb-structure-utils.readthedocs.io/en/latest/utils.html#utils-str-check-add-hydrogens-module) from **biobb_structure_utils.utils.str_check_add_hydrogens**\n",
    "***"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2021-05-17 12:45:47,337 [MainThread  ] [INFO ]  check_structure -i /home/gbayarri_local/projects/BioBB/tutorials/biobb_wf_virtual-screening/biobb_wf_virtual-screening/notebooks/ebi_api/pdb_protein.pdb -o prep_receptor.pdbqt --force_save add_hydrogen --add_charges --add_mode auto\n",
      "\n",
      "2021-05-17 12:45:47,338 [MainThread  ] [INFO ]  Exit code 0\n",
      "\n",
      "2021-05-17 12:45:47,339 [MainThread  ] [INFO ]  ===============================================================================\n",
      "=                   BioBB structure checking utility v3.7.2                   =\n",
      "=                 A. Hospital, P. Andrio, J.L. Gelpi 2018-20                  =\n",
      "===============================================================================\n",
      "\n",
      "Warning: sequence features only available in mmCIF format or with external fasta input\n",
      "Structure /home/gbayarri_local/projects/BioBB/tutorials/biobb_wf_virtual-screening/biobb_wf_virtual-screening/notebooks/ebi_api/pdb_protein.pdb loaded\n",
      " Title: \n",
      " Experimental method: unknown\n",
      " Resolution: None A\n",
      "\n",
      " Num. models: 1\n",
      " Num. chains: 1 (A: Protein)\n",
      " Num. residues:  333\n",
      " Num. residues with ins. codes:  0\n",
      " Num. HETATM residues:  0\n",
      " Num. ligands or modified residues:  0\n",
      " Num. water mol.:  0\n",
      " Num. atoms:  2673\n",
      "\n",
      "Running add_hydrogen. Options: --add_charges --add_mode auto\n",
      "109 Residues requiring selection on adding H atoms\n",
      "CYS A39,A119,A162,A211\n",
      "ASP A43,A88,A101,A112,A124,A125,A145,A150,A161,A168,A205,A227,A230,A283,A292,A294,A313,A315,A316,A321,A324,A331,A335,A343\n",
      "GLU A4,A12,A19,A22,A71,A81,A97,A98,A160,A163,A192,A215,A245,A253,A286,A317,A328,A336,A344\n",
      "HIS A64,A77,A80,A107,A126,A142,A148,A199,A228,A305,A312\n",
      "LYS A15,A45,A53,A54,A66,A76,A79,A118,A121,A139,A152,A165,A233,A248,A249,A267,A287,A295,A338\n",
      "ARG A5,A10,A23,A49,A57,A67,A70,A73,A94,A136,A149,A186,A189,A220,A237,A256,A296,A330\n",
      "TYR A9,A24,A35,A69,A103,A132,A140,A188,A200,A258,A307,A311,A323,A342\n",
      "WARNING: fixing side chains, override with --no_fix_side\n",
      "Running fixside. Options: --fix all\n",
      "5 Residues with missing side chain atoms found\n",
      " GLU A4     CG,CD,OE1,OE2\n",
      " LYS A15    CG,CD,CE,NZ\n",
      " TYR A35    CG,CD1,CE1,CZ,OH,CE2,CD2\n",
      " LYS A118   CG,CD,CE,NZ\n",
      " HIS A199   CG,ND1,CE1,NE2,CD2\n",
      "Fixing side chains\n",
      "GLU A4\n",
      "  Adding new atom CG\n",
      "  Adding new atom CD\n",
      "  Adding new atom OE1\n",
      "  Adding new atom OE2\n",
      "LYS A15\n",
      "  Adding new atom CG\n",
      "  Adding new atom CD\n",
      "  Adding new atom CE\n",
      "  Adding new atom NZ\n",
      "TYR A35\n",
      "  Adding new atom CG\n",
      "  Adding new atom CD1\n",
      "  Adding new atom CE1\n",
      "  Adding new atom CZ\n",
      "  Adding new atom OH\n",
      "  Adding new atom CE2\n",
      "  Adding new atom CD2\n",
      "LYS A118\n",
      "  Adding new atom CG\n",
      "  Adding new atom CD\n",
      "  Adding new atom CE\n",
      "  Adding new atom NZ\n",
      "HIS A199\n",
      "  Adding new atom CG\n",
      "  Adding new atom ND1\n",
      "  Adding new atom CE1\n",
      "  Adding new atom NE2\n",
      "  Adding new atom CD2\n",
      "Fixed 5 side chain(s)\n",
      "Checking for steric clashes\n",
      "No severe clashes detected\n",
      "1 Steric apolar clashes detected\n",
      " TYR A35.OH   GLU A71.CD      2.531 A\n",
      "No polar_acceptor clashes detected\n",
      "No polar_donor clashes detected\n",
      "No positive clashes detected\n",
      "No negative clashes detected\n",
      "Selection: auto\n",
      "Replacing HIS A64 by HIE\n",
      "Replacing HIS A77 by HIE\n",
      "Replacing HIS A80 by HIE\n",
      "Replacing HIS A107 by HIE\n",
      "Replacing HIS A126 by HIE\n",
      "Replacing HIS A142 by HIE\n",
      "Replacing HIS A148 by HIE\n",
      "Replacing HIS A199 by HIE\n",
      "Replacing HIS A228 by HIE\n",
      "Replacing HIS A305 by HIE\n",
      "Replacing HIS A312 by HIE\n",
      "Updating partial charges and atom types\n",
      "Warning: OXT atom missing in CSER A32. Run backbone --add_atoms first\n",
      "Warning: OXT atom missing in CASP A168. Run backbone --add_atoms first\n",
      "Warning: OXT atom missing in CLEU A353. Run backbone --add_atoms first\n",
      "Total assigned charge:      -3.79\n",
      "Final Num. models: 1\n",
      "Final Num. chains: 1 (A: Protein)\n",
      "Final Num. residues:  333\n",
      "Final Num. residues with ins. codes:  0\n",
      "Final Num. HETATM residues:  0\n",
      "Final Num. ligands or modified residues:  0\n",
      "Final Num. water mol.:  0\n",
      "Final Num. atoms:  5407\n",
      "Structure saved on prep_receptor.pdbqt\n",
      "\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "0"
      ]
     },
     "execution_count": 39,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from biobb_structure_utils.utils.str_check_add_hydrogens import str_check_add_hydrogens\n",
    "\n",
    "prep_receptor = \"prep_receptor.pdbqt\"\n",
    "prop = {\n",
    "    \"charges\": True,\n",
    "    \"mode\": \"auto\"\n",
    "}\n",
    "\n",
    "str_check_add_hydrogens(\n",
    "            input_structure_path = pdb_protein,\n",
    "            output_structure_path = prep_receptor,\n",
    "            properties=prop)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id=\"docking\"></a>\n",
    "***\n",
    "## Running the Docking\n",
    "Running the **docking process** with the prepared files:\n",
    "- **ligand**\n",
    "- **target protein**\n",
    "- **binding site box**<br>\n",
    "\n",
    "using **AutoDock Vina**. <br>\n",
    "\n",
    "***\n",
    "**Building Blocks** used:\n",
    " - [autodock_vina_run](https://biobb-vs.readthedocs.io/en/latest/vina.html#module-vina.autodock_vina_run) from **biobb_vs.vina.autodock_vina_run**\n",
    "***"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2021-05-17 12:45:49,398 [MainThread  ] [INFO ]  prep_receptor.pdbqt file ends with END, cleaning\n",
      "2021-05-17 12:45:49,405 [MainThread  ] [INFO ]  Executing AutoDock Vina\n",
      "2021-05-17 12:45:49,406 [MainThread  ] [INFO ]  Not using any container\n",
      "2021-05-17 12:46:27,195 [MainThread  ] [INFO ]  vina --ligand prep_ligand.pdbqt --receptor prep_receptor.pdbqt --center_x=23.913 --center_y=-2.702 --center_z=-23.513 --size_x=17.776 --size_y=23.257 --size_z=22.986 --out output_vina.pdbqt --log output_vina.log\n",
      "\n",
      "2021-05-17 12:46:27,196 [MainThread  ] [INFO ]  Exit code 0\n",
      "\n",
      "2021-05-17 12:46:27,197 [MainThread  ] [INFO ]  #################################################################\n",
      "# If you used AutoDock Vina in your work, please cite:          #\n",
      "#                                                               #\n",
      "# O. Trott, A. J. Olson,                                        #\n",
      "# AutoDock Vina: improving the speed and accuracy of docking    #\n",
      "# with a new scoring function, efficient optimization and       #\n",
      "# multithreading, Journal of Computational Chemistry 31 (2010)  #\n",
      "# 455-461                                                       #\n",
      "#                                                               #\n",
      "# DOI 10.1002/jcc.21334                                         #\n",
      "#                                                               #\n",
      "# Please see http://vina.scripps.edu for more information.      #\n",
      "#################################################################\n",
      "\n",
      "Detected 8 CPUs\n",
      "Reading input ... done.\n",
      "Setting up the scoring function ... done.\n",
      "Analyzing the binding site ... done.\n",
      "Using random seed: 579666017\n",
      "Performing search ... \n",
      "0%   10   20   30   40   50   60   70   80   90   100%\n",
      "|----|----|----|----|----|----|----|----|----|----|\n",
      "***************************************************\n",
      "done.\n",
      "Refining results ... done.\n",
      "\n",
      "mode |   affinity | dist from best mode\n",
      "     | (kcal/mol) | rmsd l.b.| rmsd u.b.\n",
      "-----+------------+----------+----------\n",
      "   1         -6.7      0.000      0.000\n",
      "   2         -5.9      1.645      2.130\n",
      "   3         -5.8      3.272      4.492\n",
      "   4         -5.7      2.937      3.180\n",
      "   5         -5.7      3.112      3.826\n",
      "   6         -5.6      3.252      3.689\n",
      "   7         -5.5      5.079      5.837\n",
      "   8         -5.5      4.930      5.500\n",
      "   9         -5.2      9.937     14.436\n",
      "Writing output ... done.\n",
      "\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "0"
      ]
     },
     "execution_count": 40,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from biobb_vs.vina.autodock_vina_run import autodock_vina_run\n",
    "\n",
    "output_vina_pdbqt = \"output_vina.pdbqt\"\n",
    "output_vina_log = \"output_vina.log\"\n",
    "\n",
    "autodock_vina_run(input_ligand_pdbqt_path = prep_ligand,\n",
    "             input_receptor_pdbqt_path = prep_receptor,\n",
    "             input_box_path = output_box,\n",
    "            output_pdbqt_path = output_vina_pdbqt,\n",
    "             output_log_path = output_vina_log)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id=\"viewDocking\"></a>\n",
    "### Visualizing docking output poses\n",
    "Visualizing the generated **docking poses** for the **ligand**, using **NGL viewer**. <br>\n",
    "- **Left panel**: **Docking poses** displayed with atoms coloured by **partial charges** and **licorice** representation.\n",
    "- **Right panel**: **Docking poses** displayed with atoms coloured by **element** and **ball-and-stick** representation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 62,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "926f782aecb64729a1281573e41a00e3",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(NGLWidget(), NGLWidget()))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "models = 'all'\n",
    "\n",
    "v0 = nglview.show_structure_file(output_vina_pdbqt, default=False)\n",
    "v0.add_representation(repr_type='licorice', \n",
    "                        selection=models,\n",
    "                       colorScheme= 'partialCharge')\n",
    "v0.center()\n",
    "v1 = nglview.show_structure_file(output_vina_pdbqt, default=False)\n",
    "v1.add_representation(repr_type='ball+stick', \n",
    "                        selection=models)\n",
    "v1.center()\n",
    "\n",
    "v0._set_size('500px', '')\n",
    "v1._set_size('500px', '')\n",
    "\n",
    "def on_change(change):\n",
    "    v1._set_camera_orientation(change['new'])\n",
    "    \n",
    "v0.observe(on_change, ['_camera_orientation'])\n",
    "\n",
    "HBox([v0, v1])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<img src='ngl6.png'></img>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id=\"selectPose\"></a>\n",
    "### Select Docking Pose\n",
    "Select a specific **docking pose** from the output list for **visual inspection**.\n",
    "<br>\n",
    "Choose a **docking pose** from the **DropDown list**."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "e9cd94591b19433697b6081910665ebd",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Dropdown(description='Sel. model:', options=(('model0', 0), ('model1', 1), ('model2', 2), ('model3', 3), ('mod…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from Bio.PDB import PDBParser\n",
    "parser = PDBParser(QUIET = True)\n",
    "structure = parser.get_structure(\"protein\", output_vina_pdbqt)\n",
    "models = []\n",
    "for i, m in enumerate(structure):\n",
    "    models.append(('model' + str(i), i))\n",
    "    \n",
    "mdsel = ipywidgets.Dropdown(\n",
    "    options=models,\n",
    "    description='Sel. model:',\n",
    "    disabled=False,\n",
    ")\n",
    "display(mdsel)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id=\"extractPose\"></a>\n",
    "***\n",
    "## Extract a Docking Pose\n",
    "Extract a specific **docking pose** from the **docking** outputs. <br>\n",
    "\n",
    "***\n",
    "**Building Blocks** used:\n",
    " - [extract_model_pdbqt](https://biobb-vs.readthedocs.io/en/latest/utils.html#module-utils.extract_model_pdbqt) from **biobb_vs.utils.extract_model_pdbqt**\n",
    "***"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2021-05-17 12:46:43,493 [MainThread  ] [INFO ]  Saving model 1 to output_model.pdbqt\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "0"
      ]
     },
     "execution_count": 43,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from biobb_vs.utils.extract_model_pdbqt import extract_model_pdbqt\n",
    "\n",
    "output_pdbqt_model = \"output_model.pdbqt\"\n",
    "prop = {\n",
    "    \"model\": mdsel.value + 1\n",
    "}\n",
    "\n",
    "extract_model_pdbqt(input_pdbqt_path = output_vina_pdbqt,\n",
    "             output_pdbqt_path = output_pdbqt_model,\n",
    "            properties=prop)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id=\"pdbqt2pdb\"></a>\n",
    "***\n",
    "## Converting Ligand Pose to PDB format\n",
    "Converting **ligand pose** to **PDB format**. <br>\n",
    "\n",
    "***\n",
    "**Building Blocks** used:\n",
    " - [babel_convert](https://biobb-chemistry.readthedocs.io/en/latest/babelm.html#module-babelm.babel_convert) from **biobb_chemistry.babelm.babel_convert**\n",
    "***"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2021-05-17 12:46:45,912 [MainThread  ] [INFO ]  Value  is not compatible as a coordinates value\n",
      "2021-05-17 12:46:45,913 [MainThread  ] [INFO ]  Not using any container\n",
      "2021-05-17 12:46:45,966 [MainThread  ] [INFO ]  obabel -ipdbqt output_model.pdbqt -opdb -Ooutput_model.pdb  \n",
      "\n",
      "2021-05-17 12:46:45,967 [MainThread  ] [INFO ]  Exit code 0\n",
      "\n",
      "2021-05-17 12:46:45,968 [MainThread  ] [INFO ]  1 molecule converted\n",
      "\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "0"
      ]
     },
     "execution_count": 44,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from biobb_chemistry.babelm.babel_convert import babel_convert\n",
    "\n",
    "output_pdb_model = \"output_model.pdb\"\n",
    "prop = {\n",
    "    \"input_format\": \"pdbqt\",\n",
    "    \"output_format\": \"pdb\",\n",
    "    \"obabel_path\": \"obabel\"\n",
    "}\n",
    "\n",
    "babel_convert(input_path = output_pdbqt_model,\n",
    "             output_path = output_pdb_model,\n",
    "            properties=prop)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id=\"catPdb\"></a>\n",
    "***\n",
    "## Superposing Ligand Pose to the Target Protein Structure\n",
    "Superposing **ligand pose** to the target **protein structure**, in order to see the **protein-ligand docking conformation**. <br><br>Building a new **PDB file** with both **target and ligand** (binding pose) structures. <br>\n",
    "\n",
    "***\n",
    "**Building Blocks** used:\n",
    " - [cat_pdb](https://biobb-structure-utils.readthedocs.io/en/latest/utils.html#module-utils.cat_pdb) from **biobb_structure_utils.utils.cat_pdb**\n",
    "***"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2021-05-17 12:46:48,467 [MainThread  ] [INFO ]  File output_structure.pdb created\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "0"
      ]
     },
     "execution_count": 45,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from biobb_structure_utils.utils.cat_pdb import cat_pdb\n",
    "\n",
    "output_structure = \"output_structure.pdb\"\n",
    "\n",
    "cat_pdb(#input_structure1 = pdb_single_chain,\n",
    "        input_structure1 = download_pdb,\n",
    "             input_structure2 = output_pdb_model,\n",
    "             output_structure_path = output_structure)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id=\"viewFinal\"></a>\n",
    "### Comparing final result with experimental structure \n",
    "Visualizing and comparing the generated **protein-ligand** complex with the original **protein-ligand conformation** (downloaded from the PDB database), using **NGL viewer**. <br>\n",
    "- **Licorice, element-colored** representation: **Experimental pose**.\n",
    "- **Licorice, green-colored** representation: **Docking pose**.\n",
    "<br>\n",
    "\n",
    "Note that outputs from **AutoDock Vina** don't contain all the atoms, as the program works with a **united-atom representation** (i.e. only polar hydrogens)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "f8d4e5f6d31a46798ff82197694c9820",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "NGLWidget()"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "view = nglview.NGLWidget()\n",
    "\n",
    "# v1 = Experimental Structure\n",
    "v1 = view.add_component(download_pdb)\n",
    "\n",
    "v1.clear()\n",
    "v1.add_representation(repr_type='licorice', \n",
    "                     selection='[1N1]',\n",
    "                     radius=0.5)\n",
    "\n",
    "# v2 = Docking result\n",
    "v2 = view.add_component(output_structure)\n",
    "v2.clear()\n",
    "v2.add_representation(repr_type='cartoon', colorScheme = 'sstruc')\n",
    "v2.add_representation(repr_type='licorice', radius=0.5, color= 'green', selection='UNL')\n",
    "\n",
    "view._remote_call('setSize', target='Widget', args=['','600px'])\n",
    "view\n",
    "\n",
    "# align reference and output\n",
    "code = \"\"\"\n",
    "var stage = this.stage;\n",
    "var clist_len = stage.compList.length;\n",
    "var i = 0;\n",
    "var s = [];\n",
    "for(i = 0; i <= clist_len; i++){\n",
    "    if(stage.compList[i] != undefined && stage.compList[i].structure != undefined) {        \n",
    "       s.push(stage.compList[i])\n",
    "    }\n",
    "}\n",
    "NGL.superpose(s[0].structure, s[1].structure, true, \".CA\")\n",
    "s[ 0 ].updateRepresentations({ position: true })\n",
    "s[ 0 ].autoView()\n",
    "\"\"\"\n",
    "\n",
    "view._execute_js_code(code)\n",
    "\n",
    "\n",
    "\n",
    "view.render_image()\n",
    "view.download_image(filename='ngl7.png')\n",
    "view"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<img src='ngl7.png'></img>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "***\n",
    "<a id=\"questions\"></a>\n",
    "\n",
    "## Questions & Comments\n",
    "\n",
    "Questions, issues, suggestions and comments are really welcome!\n",
    "\n",
    "* GitHub issues:\n",
    "    * [https://github.com/bioexcel/biobb](https://github.com/bioexcel/biobb)\n",
    "\n",
    "* BioExcel forum:\n",
    "    * [https://ask.bioexcel.eu/c/BioExcel-Building-Blocks-library](https://ask.bioexcel.eu/c/BioExcel-Building-Blocks-library)\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
